<script setup lang="ts">
defineOptions({
  name: "Dingwei"
});

import { ref, reactive, toRaw, onMounted, onBeforeMount } from "vue";
import apiService from "@/services/apiService";
import { conversionUtcDate, base64ToExcelAndDownload } from "@/utils/auth";
import { shallowRef } from "@vue/reactivity"; //改变监听
import { v4 as uuidv4 } from "uuid";
import AMapLoader from "@amap/amap-jsapi-loader";
import { ElMessageBox } from "element-plus";
import { GetDevicesWithPaging } from "@/api/api";
import { setToken, getToken } from "@/utils/auth";
import { useRouter } from "vue-router";
const router = useRouter();
// const map = ref(null);
var map: any = shallowRef(null); //设置监听
const ALLmarkers = ref<any>([
  { position: [116.405285, 39.904989], title: "Marker 1" }
  // { position: [116.448261, 39.921984], title: "Marker 2" }
]);
const initMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: "e344425544e4543eb4008c4904df542f"
  };
  AMapLoader.load({
    key: "fd5b2eba3a5fce51f09d27832c9e7f09", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      "AMap.Geolocation",
      "AMap.Polygon",
      "AMap.Geocoder",
      "AMap.AutoComplete",
      "AMap.PlaceSearch",
      "AMap.MouseTool",
      "AMap.Walking",
      "AMap.Driving"
    ] //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then(AMap => {
      map = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 11 // 初始化地图级别
        // center: [116.397428, 39.90923] // 初始化地图中心点位置
      });

      // 创建定位实例
      const geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, // 是否使用高精度定位，默认:true
        timeout: 10000, // 超过10秒后停止定位，默认：无穷大
        buttonPosition: "LB", // 定位按钮的停靠位置
        buttonOffset: new AMap.Pixel(10, 20), // 定位按钮的偏移量
        zoomToAccuracy: false // 定位成功后是否自动调整地图视野到定位点
      });

      // 添加定位插件
      map.addControl(geolocation);

      ALLmarkers.value.forEach(marker => {
        const newMarker = new AMap.Marker({
          position: marker.position,
          title: marker.title,
          id: marker.id,
          map: map,
          offset: new AMap.Pixel(0, 0) // 设置偏移量为(0, 0)
          // extData: {
          //   id: marker.id // 假设id从1开始递增
          // }
          // icon: new AMap.Icon({
          //   size: new AMap.Size(30, 30), // 图标尺寸
          //   image: "../../icons/svg/地图标记(在范围).png", // 本地图片路径
          //   imageSize: new AMap.Size(30, 30), // 图标显示大小
          // }),
        });

        newMarker.on("click", function (e) {
          console.log("点击了标记点：", marker.title);
          console.log("经纬度：", e.lnglat.lng, e.lnglat.lat);
          console.log("Id:", marker.id);
          console.log(marker.location);
          
          // console.log("ID:", newMarker.getExtData().id);
          // 将地图中心点设置为标记点的位置
          // this.map.setCenter([e.lnglat.lng, e.lnglat.lat]);
          // 设置地图缩放级别以便于更好地展示标记点
          // this.map.setZoom(17);
          // this.activeNames = newMarker.getExtData().id;
          // console.log(this.activeNames);
          // 可根据需要输出更多标记点信息
          //
          const createContent = () => {
            return `<div>
              <h3>姓名:${marker.title}</h3>
              <p>地址:${marker.location}</p>
              <p>经度:${e.lnglat.lng}</p>
              <p>纬度:${e.lnglat.lat}</p>
               <button onclick="go_weilan('${marker.id}')">查看电子围栏</button>
                 </div>`;
          };
          const infoWindow = new AMap.InfoWindow({
            // isCustom: true,//使用自定义窗口
            content: createContent(),
            offset: new AMap.Pixel(0, -30)
          });

          infoWindow.open(map, e.target.getPosition());
        });
      });
    })
    .catch(e => {
      console.log(e);
    });
};
import { useUserStoreHook } from "@/store/modules/user";
const UserStore = useUserStoreHook();
//弹窗点击事件调用
//@ts-ignore
window.go_weilan = id => {
  console.log("当前用户ID", id);
  router.push({
    // path: "/binghuan/dianziweilan",
    name: "Dianziweilan"
    // state: {id:id}
  });
  //@ts-ignore
  UserStore.now_user = id;
};

//获取用户定位数据
const GetList = () => {
  const data = ref({
    token: getToken().accessToken,
    body: {
      pageNumber: 1,
      pageSize: 1000
    }
  });
  ALLmarkers.value = [];
  GetDevicesWithPaging(data.value)
    .then((res: any) => {
      res.data.results.forEach(item => {
        if (item.location != null) {
          ALLmarkers.value.push({
            position: [item.location.longitude, item.location.latitude],
            title: item.name,
            id: item.userId,
            location: item.location.address
          });
        }
      });
      console.log("当前定位数据:", ALLmarkers.value);

      initMap();
    })
    .catch((err: any) => {
      console.log(err);
    });
};

onMounted(() => {
  GetList();
});
</script>

<template>
  <div ref="container" id="container"></div>
</template>

<style lang="scss" scoped>
#container {
  width: 100%;
  height: 89vh;
  margin: 0;
  // z-index: 99;
}
</style>
